package com.yipao.admin.web.goods;

import com.yipao.core.util.ResponseUtil;
import com.yipao.db.domain.goods.GoodsFormulaAttr;
import com.yipao.db.service.goods.GoodsFormulaAttrService;
import com.yipao.db.service.goods.GoodsFormulaService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 商品配方属性
 *
 * @author tianhao
 * @date 2020/5/24 23:32
 **/
@RestController
@RequestMapping("/admin/goods/formula/attr")
@Validated
public class AdminGoodsFormulaAttrController {
    @Resource
    private GoodsFormulaAttrService goodsFormulaAttrService;
    @Resource
    private GoodsFormulaService goodsFormulaService;

    /**
     * 新增
     *
     * @param goodsFormulaAttr
     * @return
     */
    @PostMapping("/insert")
    public Object insert(@RequestBody GoodsFormulaAttr goodsFormulaAttr) {
        goodsFormulaAttrService.insert(goodsFormulaAttr);
        return ResponseUtil.ok(goodsFormulaAttr);
    }

    /**
     * 修改
     *
     * @param goodsFormulaAttr
     * @return
     */
    @PostMapping("/update")
    public Object update(@RequestBody GoodsFormulaAttr goodsFormulaAttr) {
        goodsFormulaAttrService.update(goodsFormulaAttr);
        return ResponseUtil.ok();
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Object delete(@PathVariable("id") Integer id) {
        GoodsFormulaAttr goodsFormulaAttr = goodsFormulaAttrService.queryFormulaAttrById(id);
        if (goodsFormulaAttr == null || goodsFormulaAttr.getId() == null) {
            return ResponseUtil.fail(ResponseUtil.STATUS_CODE_UN_AUTH, "删除失败,数据不存在或已被删除");
        }
        // 如果配方属性被配方使用,则不能删除
        int count = goodsFormulaService.queryCountFormulaAttrByAttrId(id, goodsFormulaAttr.getCode());
        if (count > 0) {
            return ResponseUtil.fail(ResponseUtil.STATUS_CODE_UN_AUTH, "删除失败,请先删除对应的配方");
        }
        goodsFormulaAttrService.delete(id);
        return ResponseUtil.ok();
    }
}
